package cn.findviewbydream.evil.main.controller;

import cn.findviewbydream.evil.main.enums.LoginType;
import cn.findviewbydream.evil.main.service.LoginService;
import cn.findviewbydream.evil.main.utils.Utils;
import cn.findviewbydream.evil.main.utils.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/********************************************
 * 工程名：HebeuCS
 * 包名：cn.findviewbydream.evil.main.controller
 * 时间：16-10-31 下午6:58
 * 作者：白雨濃 evil
 * 邮箱：evilbai@foxmail.com
 * 内容：包含登录和注册（仅对部分人员开放）
 ********************************************/
@Controller
public class LoginController
{
    private final LoginService loginService;

    @Autowired
    public LoginController(LoginService loginService)
    {
        this.loginService = loginService;
    }

    /**
     * 登录界面
     *
     * @return
     */
    @RequestMapping("/login")
    public String login()
    {
        return "login";
    }

    /**
     * 提交登录
     *
     * @param userName
     * @param userPassword
     * @param remember
     * @return
     */
    @RequestMapping(value = "/login/submit",
            method = RequestMethod.POST,
            produces = {"text/html;charset=UTF-8"})
    @ResponseBody
    public String submit(HttpSession session,
                         String userName,
                         String userPassword,
                         @RequestParam(required = false) boolean remember)
    {
        LoginType loginType = loginService.login(session, userName, userPassword);

        String cookies = "";
        if (loginType == LoginType.SUCCESS || loginType == LoginType.ADMIN)
            cookies = loginService.setCookie(userName, userPassword, remember);
        return loginType.getState() + cookies;
    }

    /**
     * 退出登录
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "/login/exit")
    public String exit(HttpSession session)
    {
        if (loginService.exit(session))
            return WebUtil.redirect("/index");
        else
            return WebUtil.redirect("/index");
    }

    /**
     * 注册
     *
     * @param userName
     * @param userPassword
     * @param userRealName
     * @return
     */
    @RequestMapping(value = "/register/submit",
            method = RequestMethod.POST,
            produces = {"text/html;charset=UTF-8"})
    @ResponseBody
    public String register(String userName,
                           String userPassword,
                           String userRealName)
    {
        return loginService.register(userName, userPassword, userRealName).getState();
    }

}
